package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOWS_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    IUserService userService;

    /**
     * 关注或取关
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //判段登录
        Long userId = UserHolder.getUser().getId();
        if (userId==null){
            return Result.fail("请先登录");
        }
        //判段是关注还是取关
        if (isFollow){
            //关注
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            //关注成功，将其放置到Redis的set集合中！因为set集合可以实现交际
            if(isSuccess){
                //关注成功，将数据放入Redis中
                stringRedisTemplate.opsForSet().add(FOLLOWS_KEY+userId,followUserId.toString());
            }
            return isSuccess?Result.ok():Result.fail("关注失败");
        }else {
            //取关，删除
            LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Follow::getUserId,userId);
            queryWrapper.eq(Follow::getFollowUserId,followUserId);
            boolean isSuccess = remove(queryWrapper);
            if(isSuccess){
                //取关成功，将数据从Redis中移除
                stringRedisTemplate.opsForSet().remove(FOLLOWS_KEY+userId,followUserId.toString());
            }
            return isSuccess?Result.ok():Result.fail("取关失败");
        }
    }

    @Override
    public Result isFollow(Long followUserId) {
        //查询是否关注
        Long userId = UserHolder.getUser().getId();
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getUserId,userId);
        queryWrapper.eq(Follow::getFollowUserId,followUserId);
        int count = (int) count(queryWrapper);
        return count>0?Result.ok(true):Result.ok(false);
    }

    @Override
    public Result followCommons(Long id) {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //校验是否登入
        if (userId==null){
            return Result.fail("请先登入");
        }
        String key = FOLLOWS_KEY+id;
        String key2 = FOLLOWS_KEY+userId;
        //获取交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if (intersect==null||intersect.isEmpty()){
            //没有交集
            return Result.ok(0);
        }
        //解析ids集合
        List<Long> collect = intersect.stream()//集合转流
                .map(Long::valueOf) //流中元素转Long
                .collect(Collectors.toList());//转为List
        // 查询用户
        List<User> users = userService.listByIds(collect);
        //转化成UserDTO
        List<UserDTO> userDTOS = users.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
}
